import query from '@dfeidao/atom-nodejs/db/query';

// import { IBaseTable } from '@feidao/web/atom/nodejs/db/interfaces';
interface Message {
	productid: string;
	group_id: string;
	role_allot_id: string;
}
interface Data {
	group_id: string;
	priority: string;
}

export default async function atom(msg: Message, action_id: string, session_id: string, spaceid: string) {
	const systemid = '12';
	const { exec, prepare } = query(action_id, session_id, systemid);
	const productid = msg.productid;
	const role_allot_id = msg.role_allot_id;
	const group_id = msg.group_id;
	prepare('allot_conditions_group', ['group_id', 'priority'], { $or: [{ productid, role_allot_id, group_id }, { productid, role_allot_id, parent_group_id: group_id }] }, 200, 1, ['priority'], []);
	const [data1] = await exec<Data>();

	const arr = data1.map((v) => {
		return v.group_id;
	});

	prepare('allot_conditions', ['connector', 'group_id', 'field', 'operate', 'field_value', 'priority'], { productid, group_id: { $in: arr } }, 200, 1, ['group_id'], []);
	const [data] = await exec();
	// console.log(data)
	const dataArray = data.map((item: { group_id: string, group: string }) => {
		const group_id1 = item.group_id;
		const ck_data = data1.filter((d) => {
			return d.group_id === group_id1;
		});
		const arrr = new Array();
		ck_data.map((i) => {
			const group = 'group_' + i.priority;
			arrr.push(group);
			return;
		});
		item.group = arr[0] ? arr[0] : "";
		// item["group"] = arr[0] ? arr[0] : "";
		return item;
	});

	const compare = function foo(obj1: { group: string }, obj2: { group: string }) {
		const val1 = obj1.group;
		const val2 = obj2.group;
		if (val1 < val2) {
			return -1;
		} else if (val1 > val2) {
			return 1;
		} else {
			return 0;
		}
	};
	dataArray.sort(compare);
	return { dataArray, count: dataArray.length };
}
